﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using System.Text;
using System.Threading;

namespace VSM
{
    public partial class Forecasts : System.Web.UI.Page
    {
        public static DataTable dtContents;
        public static DataTable dtHeader;
        private static GeneralFunctions GF = null;
        private string TblHeaderName = "OFCT";
        private string TblLineName = "FCT1";
        private string CurrentPageUrl = "/Business/Purchasing/Forecasts.aspx";
        private string HeaderKeyName = "DocEntry";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Session[Utils.AppConstants.ID_User] == null || Session[Utils.AppConstants.Password] == null || Session[Utils.AppConstants.ID_Dealer] == null)
                    Response.Redirect("../../Login.aspx");

                if (!IsPostBack)
                {
                    ClearScreen();

                    //DateTime startdate = Convert.ToDateTime("01/01/" + txtStartMonthYear.Text);
                    //DateTime enddate = Convert.ToDateTime("12/01/" + txtStartMonthYear.Text);

                    MasterData masterDataWS = new MasterData();
                    string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                    Session["FCGF"] = GF;
                    
                    String fcId = Request.QueryString["fc_id"];
                    if (!String.IsNullOrEmpty(fcId)) // display FC from chosen list
                        LoadData(fcId, ConvertDocType.Get2String(DocType.SALES_FORECASTS)); //, startdate, enddate
                    else // display default 
                    {
                        string SQLCommand = "select isNull(Max(AbsID), 0) AbsID from OFCT where StartDate = " 
                            + " (select Max(StartDate) from OFCT where U_DealerID = '" + Session[Utils.AppConstants.ID_Dealer].ToString() + "' and YEAR(StartDate) = " + txtStartMonthYear.Text.Trim() + ")";
                        string lsAbsID = GF.GetSingleValue(dbType, SQLCommand, "AbsID");
                        LoadData(lsAbsID, ConvertDocType.Get2String(DocType.SALES_FORECASTS)); //, startdate, enddate
                        if(lsAbsID.Equals("0")) SetScreenStatus("New");
                    }

                    //String BaseEntry = Request.QueryString["base_entry"];
                    //if (!String.IsNullOrEmpty(BaseEntry))
                    //{
                    //    String BaseType = Request.QueryString["base_type"];
                    //    LoadData(BaseEntry, BaseType, startdate, enddate);
                    //}
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";

                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                // Load Model
                DropDownList ddlModel = (DropDownList)e.Row.FindControl("ddlModel");
                HiddenField hdnModel = (HiddenField)e.Row.FindControl("hdnModel");
                if (ddlModel != null)
                {
                    ddlModel.DataSource = GF.GetModelList(dbType);
                    ddlModel.DataValueField = "Code";
                    ddlModel.DataTextField = "Name";
                    ddlModel.DataBind();
                    ddlModel.Items.Insert(0, "");
                    if (hdnModel != null) ddlModel.SelectedValue = hdnModel.Value;
                }
                // Load Product
                DropDownList ddlProduct = (DropDownList)e.Row.FindControl("ddlProduct");
                if (ddlProduct != null)
                {
                    LoadGridProduct(ddlModel, ddlProduct);
                    HiddenField hdnProduct = (HiddenField)e.Row.FindControl("hdnProduct");
                    if (hdnProduct != null) ddlProduct.SelectedValue = hdnProduct.Value;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblItemCode = (Label)row.FindControl("lblItemCode");
                DataTable tb = (DataTable)Session["FCT1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString()))
                            {
                                dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                            }
                        }
                        tb.Rows.Remove(rupdate[0]);
                    }
                    this.grvFCT1.EditIndex = -1;
                    BindData((DataTable)Session["FCT1Table"]);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dtContent"></param>
        /// <param name="startdate"></param>
        /// <param name="enddate"></param>
        /// <returns></returns>
        private DataTable BuildContents(DataTable dtContent) //, DateTime startdate, DateTime enddate
        {
            string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            int i = 1;
            DataTable dt = new DataTable("FCT1");
            dt.Columns.Add("ItemCode");
            dt.Columns.Add("ItemName");
            dt.Columns.Add("No");
            dt.Columns.Add("U_Model");
            dt.Columns.Add("U_Color");
            dt.Columns.Add("U_Product");
            dt.Columns.Add("Quantity_01");
            dt.Columns.Add("LineID_01");
            dt.Columns.Add("Quantity_02");
            dt.Columns.Add("LineID_02");
            dt.Columns.Add("Quantity_03");
            dt.Columns.Add("LineID_03");
            dt.Columns.Add("Quantity_04");
            dt.Columns.Add("LineID_04");
            dt.Columns.Add("Quantity_05");
            dt.Columns.Add("LineID_05");
            dt.Columns.Add("Quantity_06");
            dt.Columns.Add("LineID_06");
            dt.Columns.Add("Quantity_07");
            dt.Columns.Add("LineID_07");
            dt.Columns.Add("Quantity_08");
            dt.Columns.Add("LineID_08");
            dt.Columns.Add("Quantity_09");
            dt.Columns.Add("LineID_09");
            dt.Columns.Add("Quantity_10");
            dt.Columns.Add("LineID_10");
            dt.Columns.Add("Quantity_11");
            dt.Columns.Add("LineID_11");
            dt.Columns.Add("Quantity_12");
            dt.Columns.Add("LineID_12");

            if (dtContent != null)
            {
                string ItemCode = String.Empty;
                DataRow newRow = null;

                foreach (DataRow dr in dtContent.Rows)
                {
                    Double decQty = Double.Parse(String.IsNullOrEmpty(dr["Quantity"].ToString()) ? "0" : dr["Quantity"].ToString());
                    if (decQty < 1) decQty = 0;

                    if (ItemCode != dr["ItemCode"].ToString())
                    {
                        if (newRow != null) dt.Rows.Add(newRow);
                        newRow = dt.NewRow();

                        newRow["ItemCode"] = ItemCode = dr["ItemCode"].ToString();
                        newRow["ItemName"] = dr["ItemName"].ToString();
                        newRow["U_Model"] = dr["U_ModelSales"].ToString();
                        newRow["U_Color"] = dr["U_Color"].ToString();
                        newRow["U_Product"] = dr["U_ProductSales"].ToString();

                        newRow["Quantity_" + Convert.ToDateTime(dr["Date"].ToString(), (new System.Globalization.CultureInfo("es-US")) as CultureInfo).ToString("MM")] = GF.FormatNumeric(decQty.ToString(), "QtyDec");
                        newRow["LineID_" + Convert.ToDateTime(dr["Date"].ToString(), (new System.Globalization.CultureInfo("es-US")) as CultureInfo).ToString("MM")] = dr["LineID"];
                    }
                    else
                    {
                        newRow["Quantity_" + Convert.ToDateTime(dr["Date"].ToString(), (new System.Globalization.CultureInfo("es-US")) as CultureInfo).ToString("MM")] = GF.FormatNumeric(decQty.ToString(), "QtyDec");
                        newRow["LineID_" + Convert.ToDateTime(dr["Date"].ToString(), (new System.Globalization.CultureInfo("es-US")) as CultureInfo).ToString("MM")] = dr["LineID"];
                    }
                }
                if (newRow != null) dt.Rows.Add(newRow);
            }
            return dt;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="docEntry"></param>
        /// <param name="type"></param>
        private void LoadData(string AbsID, string NewDocType) // , DateTime startdate, DateTime enddate
        {
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            Transaction ts = new Transaction();
            DataSet returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, AbsID, dbType);

            if (returnDoc == null) returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, "1", dbType);

            if (returnDoc == null || returnDoc.Tables.Count < 2)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('No record found!','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return;
            }

            dtHeader = returnDoc.Tables[0];
            DataRow dr = null;
            if (dtHeader.Rows.Count > 0)
            {
                dr = dtHeader.Rows[0];
                this.hdnAbsID.Value = AbsID;
                this.txtFCCode.Text = dr["Code"].ToString();
                this.txtFCName.Text = dr["Name"].ToString();
                txtStartMonthYear.Text = String.Format("{0:yyyy}", Convert.ToDateTime(dr["StartDate"], (new System.Globalization.CultureInfo("es-US")) as CultureInfo));
                ViewState["StartMonthYear"] = txtStartMonthYear.Text;
            }
            else
            {
                this.hdnAbsID.Value = "0";
                this.txtFCCode.Text =
                this.txtFCName.Text = string.Empty;
                txtStartMonthYear.Text = String.Format("{0:yyyy}", Convert.ToDateTime(DateTime.Now.ToString("MM/dd/yyyy"), (new System.Globalization.CultureInfo("es-US")) as CultureInfo));
                ViewState["StartMonthYear"] = txtStartMonthYear.Text;
            }
            SetScreenStatus("Update");
            dtContents = BuildContents(returnDoc.Tables[1]); //, startdate, enddate

            BindData(dtContents);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblData"></param>
        private void BindData(DataTable tblData)
        {
            Session["FCT1Table"] = tblData;
            this.grvFCT1.DataSource = tblData;
            this.grvFCT1.DataBind();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    DataTable tblFCT1 = (DataTable)Session["FCT1Table"];
                    CultureInfo ivC = new System.Globalization.CultureInfo("es-US");
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    //DateTime startdate, enddate;

                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                        case "SelectDocList":
                            ClearScreen();
                            GridViewRow rowDocList = Session["ChosenDocList"] != null ? (GridViewRow)Session["ChosenDocList"] : null;
                            string fcId = ((Label)rowDocList.FindControl("lblAbsID")).Text;
                            string doctype = ((Label)rowDocList.FindControl("lblDocType")).Text;
                            //startdate = Convert.ToDateTime(((Label)rowDocList.FindControl("lblStartDate")).Text, (new System.Globalization.CultureInfo("es-US")) as CultureInfo);
                            //enddate = Convert.ToDateTime(((Label)rowDocList.FindControl("lblEndDate")).Text, (new System.Globalization.CultureInfo("es-US")) as CultureInfo);
                            LoadData(fcId, doctype); //, startdate, enddate
                            break;

                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                String requestXML = _collectData();
                if (requestXML == "") return;

                Transaction ts = new Transaction();
                DataSet ds = ts.CreateMarketingDocument(requestXML, ConvertDocType.Get2String(DocType.SALES_FORECASTS), hdnAbsID.Value, hdnIsUpdate.Value.Equals("true"), dbType);

                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    Session["requestXML"] = requestXML;
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    SetScreenStatus("Update");
                    //ClearScreen();
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public String _collectData()
        {
            try
            {
                //Update table header
                DataTable dtHeader = new DataTable("OFCT");
                dtHeader.Columns.Add("AbsID");
                dtHeader.Columns.Add("Code");
                dtHeader.Columns.Add("Name");
                dtHeader.Columns.Add("UserSign");
                dtHeader.Columns.Add("StartDate");
                dtHeader.Columns.Add("EndDate");
                dtHeader.Columns.Add("FormView");
                dtHeader.Columns.Add("U_DealerID");
                DataRow drHeader = dtHeader.NewRow();
                if (hdnIsUpdate.Value.Equals("true")) drHeader["AbsID"] = hdnAbsID.Value;
                drHeader["Code"] = txtFCCode.Text.Trim();
                drHeader["Name"] = txtFCName.Text.Trim();
                drHeader["StartDate"] = txtStartMonthYear.Text + "0101"; // begin of Year
                drHeader["EndDate"] = txtStartMonthYear.Text + "1231";   // end of Year
                drHeader["UserSign"] = 1;
                drHeader["FormView"] = "M";
                drHeader["U_DealerID"] = Session[Utils.AppConstants.ID_Dealer].ToString();
                dtHeader.Rows.Add(drHeader);

                DocumentXML objInfo = new DocumentXML();
                DataSet ds = new DataSet("DS");
                dtHeader.TableName = TblHeaderName;
                ds.Tables.Add(dtHeader.Copy());

                DataTable dt = new DataTable("FCT1");

                dt.Columns.Add("AbsID");
                dt.Columns.Add("LineID");
                dt.Columns.Add("ItemCode");

                dt.Columns.Add("Date");
                dt.Columns.Add("Quantity");

                DataTable tblFCT1 = (DataTable)Session["FCT1Table"];
                ApplyGV2DT(ref tblFCT1);

                DataRow rowNew = null;
                Double decQty = 0.001;
                String lsQty = "0.001";
                if (hdnIsUpdate.Value.Equals("true")) // update FC.
                {
                    foreach (DataRow dr in tblFCT1.Rows)
                    {
                        if (dr["ItemCode"].ToString().Length > 0)
                        {
                            for (int i = 1; i <= 12; i++)
                            {
                                rowNew = dt.NewRow();
                                rowNew["AbsID"] = hdnAbsID.Value;
                                rowNew["LineID"] = i;
                                rowNew["ItemCode"] = dr["ItemCode"];
                                rowNew["Date"] = txtStartMonthYear.Text + (i < 10 ? "0" + i.ToString() : i.ToString()) + "01";
                                lsQty = dr["Quantity_" + (i < 10 ? "0" + i.ToString() : i.ToString())].ToString();
                                decQty = Double.Parse((String.IsNullOrEmpty(lsQty) || lsQty.Equals("0")) ? "0.001" : lsQty);
                                rowNew["Quantity"] = decQty;
                                dt.Rows.Add(rowNew);
                            }
                        }
                    }
                }
                else // new FC.
                {
                    foreach (DataRow dr in dtContents.Rows)
                    {
                        if (dr["ItemCode"].ToString().Length > 0)
                        {
                            for (int i = 1; i <= 12; i++)
                            {
                                rowNew = dt.NewRow();
                                rowNew["LineID"] = i;
                                rowNew["ItemCode"] = dr["ItemCode"];
                                rowNew["Date"] = txtStartMonthYear.Text + (i < 10 ? "0" + i.ToString() : i.ToString()) + "01";
                                lsQty = dr["Quantity_" + (i < 10 ? "0" + i.ToString() : i.ToString())].ToString();
                                decQty = Double.Parse((String.IsNullOrEmpty(lsQty) || lsQty.Equals("0")) ? "0.001" : lsQty);
                                rowNew["Quantity"] = decQty;
                                dt.Rows.Add(rowNew);
                            }
                        }
                    }
                }

                Array arrContentsCols = new string[] { "Quantity" };
                ds.Tables.Add(GF.ResetFormatNumeric(dt, arrContentsCols).Copy());
                return objInfo.ToXMLStringFromDS(ConvertDocType.Get2String(DocType.SALES_FORECASTS), ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return "";
            }
        }
        protected void ClearScreen()
        {
            dtHeader = new DataTable(DefineTables.SALES_FORECASTS_TITLE);
            dtHeader.Columns.Add("AbsID");
            dtHeader.Columns.Add("Code");
            dtHeader.Columns.Add("Name");

            dtHeader.Columns.Add("UserSign");
            dtHeader.Columns.Add("StartDate");
            dtHeader.Columns.Add("EndDate");
            dtHeader.Columns.Add("FormView");
            dtHeader.Rows.Add();

            dtContents = new DataTable(DefineTables.SALES_FORECASTS_ROW);
            txtStartMonthYear.Text = DateTime.Now.Year.ToString();
            txtStartMonthYear.Text.ToString(System.Threading.Thread.CurrentThread.CurrentCulture as CultureInfo);

            txtFCCode.Text =
            txtFCName.Text = string.Empty;

            //DateTime startdate = Convert.ToDateTime("01/01/" + this.txtStartMonthYear.Text);
            //DateTime enddate = Convert.ToDateTime("12/31/" + this.txtStartMonthYear.Text);
            dtContents = BuildContents(null); //, startdate, enddate
            BindData(dtContents);
            SetScreenStatus("New");
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Status"></param>
        protected void SetScreenStatus(string Status)
        {
            switch (Status)
            {
                case "New":
                    btnAddItems.Enabled = 
                    btnSave.Enabled = true;
                    hdnIsUpdate.Value = "false";
                    txtFCCode.ReadOnly = false;
                    txtFCCode.BorderStyle = BorderStyle.NotSet;
                    txtFCCode.BackColor = System.Drawing.Color.Empty;
                    break;

                case "Update":
                    btnAddItems.Enabled = 
                    btnSave.Enabled = true;
                    hdnIsUpdate.Value = "true";
                    txtFCCode.ReadOnly = true;
                    txtFCCode.BorderStyle = BorderStyle.None;
                    txtFCCode.BackColor = System.Drawing.Color.Transparent;
                    break;

                case "Close":
                    btnAddItems.Enabled = 
                    btnSave.Enabled = false;
                    break;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grvFCT1.PageIndex = e.NewPageIndex;
            DataTable tblFCT1 = (DataTable)Session["FCT1Table"];
            BindData(tblFCT1);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvFCT1_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                GridViewRow myRow = e.Row;
                Label lblNo = myRow.FindControl("lblNo") as Label;
                lblNo.Text = (myRow.RowIndex + 1).ToString();

                TextBox txtQuantity = null;
                int liYear = int.Parse(string.IsNullOrEmpty((string)ViewState["StartMonthYear"]) ? DateTime.Now.Year.ToString() : (string)ViewState["StartMonthYear"]);
                if (liYear == DateTime.Now.Year) // current year
                {
                    for (int i = 1; i < DateTime.Now.Month; i++)
                    {
                        if (i < 10) txtQuantity = myRow.FindControl("txtQuantity_0" + i.ToString()) as TextBox;
                        else txtQuantity = myRow.FindControl("txtQuantity_" + i.ToString()) as TextBox;
                        if (txtQuantity != null)
                        {
                            txtQuantity.ReadOnly = true;
                            txtQuantity.BorderStyle = BorderStyle.None;
                            txtQuantity.BackColor = System.Drawing.Color.Transparent;
                        }
                    }
                }
                else if (liYear < DateTime.Now.Year) // The past Year
                {
                    for (int i = 1; i <= 12; i++)
                    {
                        if (i < 10) txtQuantity = myRow.FindControl("txtQuantity_0" + i.ToString()) as TextBox;
                        else txtQuantity = myRow.FindControl("txtQuantity_" + i.ToString()) as TextBox;
                        if (txtQuantity != null)
                        {
                            txtQuantity.ReadOnly = true;
                            txtQuantity.BorderStyle = BorderStyle.None;
                            txtQuantity.BackColor = System.Drawing.Color.Transparent;
                        }
                    }
                }

            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAddItems_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable tblFCT1 = (DataTable)Session["FCT1Table"];
                ApplyGV2DT(ref tblFCT1);
                DataRow rowNew = null;
                rowNew = tblFCT1.NewRow();
                rowNew["Quantity_01"] = 0;
                rowNew["Quantity_02"] = 0;
                rowNew["Quantity_03"] = 0;
                rowNew["Quantity_04"] = 0;
                rowNew["Quantity_05"] = 0;
                rowNew["Quantity_06"] = 0;
                rowNew["Quantity_07"] = 0;
                rowNew["Quantity_08"] = 0;
                rowNew["Quantity_09"] = 0;
                rowNew["Quantity_10"] = 0;
                rowNew["Quantity_11"] = 0;
                rowNew["Quantity_12"] = 0;

                tblFCT1.Rows.Add(rowNew);
                BindData(tblFCT1);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlModel_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlModel = (DropDownList)row.FindControl("ddlModel");
                if (ddlModel.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Model');", true);
                    ddlModel.Focus();
                    return;
                }
                HiddenField hdnModel = (HiddenField)row.FindControl("hdnModel");
                hdnModel.Value = ddlModel.SelectedValue;
                // Load Product
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct != null)
                {
                    LoadGridProduct(ddlModel, ddlProduct);
                    HiddenField hdnProduct = (HiddenField)row.FindControl("hdnProduct");
                    if (hdnProduct != null && ddlProduct.Items.FindByValue(hdnProduct.Value) != null)
                    {
                        ddlProduct.SelectedValue = hdnProduct.Value;
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlProduct_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Product');", true);
                    ddlProduct.Focus();
                    return;
                }

                HiddenField hdnProduct = (HiddenField)row.FindControl("hdnProduct");
                hdnProduct.Value = ddlProduct.SelectedValue;
              
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ddlModel"></param>
        /// <param name="ddlProduct"></param>
        private void LoadGridProduct(DropDownList ddlModel, DropDownList ddlProduct)
        {
            try
            {
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                ddlProduct.DataSource = GF.GetProductByModel(dbType, ddlModel.SelectedValue);
                ddlProduct.DataValueField = "Code";
                ddlProduct.DataTextField = "Name";
                ddlProduct.DataBind();
                ddlProduct.Items.Insert(0, "");
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblFCT1"></param>
        protected void ApplyGV2DT(ref DataTable tblFCT1)
        {
            try
            {
                tblFCT1.Rows.Clear();
                foreach (GridViewRow row in grvFCT1.Rows)
                {
                    ViewState["rowindex"] = row.RowIndex;
                    TextBox txtQuantity1 = (TextBox)row.FindControl("txtQuantity_01");
                    TextBox txtQuantity2 = (TextBox)row.FindControl("txtQuantity_02");
                    TextBox txtQuantity3 = (TextBox)row.FindControl("txtQuantity_03");
                    TextBox txtQuantity4 = (TextBox)row.FindControl("txtQuantity_04");
                    TextBox txtQuantity5 = (TextBox)row.FindControl("txtQuantity_05");
                    TextBox txtQuantity6 = (TextBox)row.FindControl("txtQuantity_06");
                    TextBox txtQuantity7 = (TextBox)row.FindControl("txtQuantity_07");
                    TextBox txtQuantity8 = (TextBox)row.FindControl("txtQuantity_08");
                    TextBox txtQuantity9 = (TextBox)row.FindControl("txtQuantity_09");
                    TextBox txtQuantity10 = (TextBox)row.FindControl("txtQuantity_10");
                    TextBox txtQuantity11 = (TextBox)row.FindControl("txtQuantity_11");
                    TextBox txtQuantity12 = (TextBox)row.FindControl("txtQuantity_12");
                    DropDownList ddlModel = (DropDownList)row.FindControl("ddlModel");
                    DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");

                    DataTable dtItem = null;
                    if (Session["FullItem"] == null)
                    {
                        MasterData obj = new MasterData();
                        string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                        DataSet ds = obj.GetItemsByModelProduct(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlModel.SelectedValue, ddlProduct.SelectedValue);
                        if (ds != null && ds.Tables.Count > 0) dtItem = ds.Tables[0];
                    }
                    else 
                        dtItem = (DataTable)Session["FullItem"];
                    
                    DataRow rupdate = tblFCT1.NewRow();
                    rupdate["U_Model"] = ddlModel.SelectedValue.ToString();
                    rupdate["U_Product"] = ddlProduct.SelectedValue.ToString();
                    if (tblFCT1 != null && dtItem != null && dtItem.Rows.Count > 0)
                    {
                        rupdate["ItemCode"] = dtItem.Rows[0]["ItemCode"].ToString();
                        rupdate["ItemName"] = dtItem.Rows[0]["ItemName"].ToString();
                    }
                    if (txtQuantity1 != null) rupdate["Quantity_01"] = txtQuantity1.Text;
                    if (txtQuantity2 != null) rupdate["Quantity_02"] = txtQuantity2.Text;
                    if (txtQuantity3 != null) rupdate["Quantity_03"] = txtQuantity3.Text;
                    if (txtQuantity4 != null) rupdate["Quantity_04"] = txtQuantity4.Text;
                    if (txtQuantity5 != null) rupdate["Quantity_05"] = txtQuantity5.Text;
                    if (txtQuantity6 != null) rupdate["Quantity_06"] = txtQuantity6.Text;
                    if (txtQuantity7 != null) rupdate["Quantity_07"] = txtQuantity7.Text;
                    if (txtQuantity8 != null) rupdate["Quantity_08"] = txtQuantity8.Text;
                    if (txtQuantity9 != null) rupdate["Quantity_09"] = txtQuantity9.Text;
                    if (txtQuantity10 != null) rupdate["Quantity_10"] = txtQuantity10.Text;
                    if (txtQuantity11 != null) rupdate["Quantity_11"] = txtQuantity11.Text;
                    if (txtQuantity12 != null) rupdate["Quantity_12"] = txtQuantity12.Text;
                    tblFCT1.Rows.Add(rupdate);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            //this.txtStartMonthYear.Text = string.IsNullOrEmpty(this.txtStartMonthYear.Text) ? DateTime.Now.Year.ToString() : this.txtStartMonthYear.Text;
            //DateTime startdate = Convert.ToDateTime("01/01/" + txtStartMonthYear.Text);
            //DateTime enddate = Convert.ToDateTime("12/01/" + txtStartMonthYear.Text);
            //ViewState["StartMonthYear"] = this.txtStartMonthYear.Text;
            LoadData("0", ConvertDocType.Get2String(DocType.SALES_FORECASTS)); //, startdate, enddate
            SetScreenStatus("New");
        }
    }
}